# from flask import Flask
# app = Flask(__name__)

# @app.route('/em/<content>', methods=['get'])
# def hello_world(content):
#     name = request.form.get("name")
#     content = emoji.emojize(content)
#     return content
#
# if __name__ == '__main__':
#     app.run(host="0.0.0.0",port=5000, debug='true'
#!/usr/bin/env python
# -*- coding: utf-8 -*-


import time
from urllib import parse
import requests
import emoji
from flask import Flask, request, jsonify, make_response
from flask_restful import Api, Resource, fields, marshal_with
from flask_cors import CORS

from flask_caching import Cache
from video_spider import get_video_info,get_user_info,get_res

import config

app = Flask(__name__)
cache = Cache(app,config={'CACHE_TYPE': 'simple'})
api = Api(app)

# CORS(app, resources=r'/*')
cookies='install_id=289921155475485; ttreq=1$e3ea8254fa0d6a9e1df75f9db63916cea8432ad3; tt_webid=b1a8f01b53188889584dc4a61db95d2f; d_ticket=5b20944a6cbeaa07f3040ece8d33dd01116f8; odin_tt=8018bfa200690e7be64f6cb84b3e6da1041e4f41da5486e8e6dbf32f05d4c9a4071c59abbe285b1bf8fc74f839686343; sid_guard=a3d55d3ce3f13998f686372707c7a72f%7C1592360220%7C5184000%7CSun%2C+16-Aug-2020+02%3A17%3A00+GMT; uid_tt=5f8507820b4533d74d5937bab890a97c; uid_tt_ss=5f8507820b4533d74d5937bab890a97c; sid_tt=a3d55d3ce3f13998f686372707c7a72f; sessionid=a3d55d3ce3f13998f686372707c7a72f; sessionid_ss=a3d55d3ce3f13998f686372707c7a72f'

class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}
    def post(self):
        if request.get_data() is None:
            return '请求参数为空'
        content = request.form.get("name")
        res=emoji.emojize(content)
        print(res)
        return {"data":res}, 200

class Hotrankings(Resource):
    # def get(self):
    #     hot_search = 'https://aweme-hl.snssdk.com/aweme/v1/hot/search/list/?detail_list=1&mac_address=08:00:27:29:D2:F5&os_api=23&device_type=MI%205s&device_platform=android&ssmix=a&iid=92152480453&manifest_version_code=860&dpi=320&uuid=008796750074613&version_code=860&app_name=aweme&version_name=8.6.0&ts=1577932778&openudid=c055533a0591b2dc&device_id=69918538596&resolution=810*1440&os_version=6.0.1&language=zh&device_brand=Xiaomi&app_type=normal&ac=wifi&update_version_code=8602&aid=1128&channel=tengxun_new&_rticket=1577932779592'
    #     headers = {
    #         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"}
    #     hot_json = requests.get(hot_search, headers=headers).json()
    #     hot_list = []
    #     active_time = hot_json['data']['active_time']  # 创建时间
    #     for data in hot_json['data']['word_list']:
    #         item = []
    #         keyword = data['word']
    #         hot_value = str(data['hot_value'])
    #         video_img = data['word_cover']['url_list'][0]  # 封面
    #         video_url = 'https://xhl97.cn/tools/douyinhot/url.php?word={}'.format(quote(keyword))
    #         item.append(keyword)
    #         item.append(hot_value)
    #         item.append(video_img)
    #         item.append(video_url)
    #         hot_list.append(item)
    #
    #     return {'active_time': active_time, "data": hot_list}, 200

    def timestamp_to_date(self,time_stamp, format_string="%Y-%m-%d %H:%M:%S"):
        time_array = time.localtime(time_stamp)
        str_date = time.strftime(format_string, time_array)
        return str_date

    def get(self):
        url = "https://creator.douyin.com/aweme/v1/creator/data/billboard/?billboard_type=1"
        headers = {
            "cookie": cookies,
            "referer": "https://creator.douyin.com/billboard/hot",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36 Edg/83.0.478.45"
        }
        response = requests.get(url=url, headers=headers).json()  # [0].get('extra_list')
        responses = response.get('billboard_data')
        update_time = response.get('extra').get('now')
        up_time = self.timestamp_to_date(update_time / 1000)
        res_list = []
        for res in responses:
            html_res = res.get('extra_list')
            for x in html_res:
                x['value'] = res.get('value')
            # value = res.get('value')
            # values={'value':value}
            # html_res.append(values)
            res_list.append(html_res)
        return {'active_time': up_time, "data": res_list}, 200

class Authors(Resource):
    def get(self):
        author=request.args.get('author')
        page=request.args.get('page')
        keyword = {
            "keyword": author
        }
        url = "https://search-hl.amemv.com/aweme/v1/search/item/?ts=1592450911&cpu_support64=false&host_abi=armeabi-v7a&_rticket=1592450911511&mac_address=B8%3A97%3A5A%3AAE%3AEA%3A1F&mcc_mnc=46007&"
        ts = str(time.time()).split(".")[0]
        _rticket = str(time.time() * 1000).split(".")[0]
        pamar2 = 'os_api=22&device_platform=android&device_type=SM-N960F&iid=289921155475485&version_code=110500&app_name=aweme&openudid=949b2709fead2b5a&device_id=78814921633816&os_version=5.1.1&aid=1128&channel=tengxun_new&ssmix=a&manifest_version_code=110501&dpi=320&cdid=7fe814bf-8ece-4f4e-874d-5f0f0a10fcd6&version_name=11.5.0&resolution=1600*900&language=zh&device_brand=samsung&app_type=normal&ac=wifi&update_version_code=11509900&uuid=355757540242340'
        params = url[url.index('?') + 1:] + pamar2
        STUB = ""
        s = config.getXGon(params, STUB, cookies)
        gorgon = config.xGorgon(ts, config.strToByte(s))
        headers = {
            'Cookie': cookies,
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'User-Agent': 'com.ss.android.ugc.aweme/110501 (Linux; U; Android 5.1.1; zh_CN; SM-N960F; Build/JLS36C; Cronet/TTNetVersion:3c28619c 2020-05-19 QuicVersion:0144d358 2020-03-24)',
            'X-Gorgon': gorgon,
            'X-Khronos': ts,
            'x-common-params-v2': pamar2
        }
        keyword = config.urlencode(keyword)
        payload = f"{keyword}&offset={page}&count=10&source=video_search&search_source=search_history&is_pull_refresh=0&hot_search=0&search_id=&query_correct_type=1&is_filter_search=0&sort_type=0&publish_time=0&enter_from=homepage_hot"
        response = requests.request("POST", url, headers=headers, data=payload)
        res=response.text.encode('utf8').decode('utf8')
        return {"data": res}, 200

class User_info(Resource):
    def get(self):
        key=request.args.get('keyword')
        page=request.args.get('page')
        keyword = parse.quote(key)
        userurl = "https://search-hl.amemv.com/aweme/v1/discover/search/?ts=1592551847&cpu_support64=false&host_abi=armeabi-v7a&_rticket=1592551848588&mac_address=B8%3A97%3A5A%3AAE%3AEA%3A1F&mcc_mnc=46007&"
        ts = str(time.time()).split(".")[0]
        _rticket = str(time.time() * 1000).split(".")[0]
        pamar2 = 'os_api=22&device_platform=android&device_type=SM-N960F&iid=289921155475485&version_code=110500&app_name=aweme&openudid=949b2709fead2b5a&device_id=78814921633816&os_version=5.1.1&aid=1128&channel=tengxun_new&ssmix=a&manifest_version_code=110501&dpi=320&cdid=7fe814bf-8ece-4f4e-874d-5f0f0a10fcd6&version_name=11.5.0&resolution=1600*900&language=zh&device_brand=samsung&app_type=normal&ac=wifi&update_version_code=11509900&uuid=355757540242340'
        params = userurl[userurl.index('?') + 1:] + pamar2
        STUB = ""
        s = config.getXGon(params, STUB, cookies)
        print()
        gorgon = config.xGorgon(ts, config.strToByte(s))
        headers = {
            'Cookie': cookies,
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'User-Agent': 'com.ss.android.ugc.aweme/110501 (Linux; U; Android 5.1.1; zh_CN; SM-N960F; Build/JLS36C; Cronet/TTNetVersion:3c28619c 2020-05-19 QuicVersion:0144d358 2020-03-24)',
            'X-Gorgon': gorgon,
            'X-Khronos': ts,
            'x-common-params-v2': pamar2
        }
        userurl = "https://search-hl.amemv.com/aweme/v1/discover/search/?ts=1592551847&cpu_support64=false&host_abi=armeabi-v7a&_rticket=1592551848588&mac_address=B8%3A97%3A5A%3AAE%3AEA%3A1F&mcc_mnc=46007&"
        userpayload = f"cursor={page}&keyword={keyword}&count=10&type=1&is_pull_refresh=0&hot_search=0&search_source=search_sug&search_id=&query_correct_type=1&enter_from=homepage_hot"
        response = requests.request("POST", userurl, headers=headers, data=userpayload)
        res=response.text.encode('utf8').decode('utf8')
        return {"data": res}, 200

class Video(Resource):
    @cache.cached(timeout=10 * 6)
    def get(self,user_id):
        info = get_video_info(user_id)
        info.sort(key=lambda i:i['create_time'], reverse=True)
        return {"data_list": info, "code": 200}

class User(Resource):
    @cache.cached(timeout=60 * 30)
    def get(self,user_id):
        info = get_user_info(user_id)
        return {"user_info": info, "code": 200}


class Sec(Resource):
    # @cache.cached(timeout=60 * 30)
    def get(self, sec_id):
        max_cursor = 0
        info_list = []
        count = 0
        get_res(sec_id,max_cursor,info_list,count)
        print(info_list)
        return {"user_info": info_list, "code": 200}


api.add_resource(HelloWorld, '/em')
api.add_resource(Hotrankings, '/ht')
api.add_resource(Authors,'/as')
api.add_resource(User_info,'/uo')
api.add_resource(Video,'/video/<string:user_id>')
api.add_resource(User,'/user/<string:user_id>')
api.add_resource(Sec,'/sec/<string:sec_id>')


if __name__ == '__main__':
    CORS(app, supports_credentials=True)
    app.run(
        host='0.0.0.0',
        port=5000,
        debug=True
    )
